﻿using AutoMapper;
using Finance.Api.Write.Applications.Commands.财务管理.ReturnMonerys;
using Finance.Domain;
using Finance.ErrorCode;
using Finance.Infrastructure;
using MediatR;
using System.Security.Claims;

namespace Finance.Api.Write.Applications.CommandHands.财务管理.ReturnMonerys
{
    public class UpdateReturnMoneryCommandHandler : IRequestHandler<UpdateReturnMoneryCommand, ApiResult<int>>
    {
        private readonly IMapper mapper;
        private readonly SqlsugarDb<ReturnMoney> db;
        private readonly IHttpContextAccessor httpContextAccessor;

        public UpdateReturnMoneryCommandHandler(IMapper mapper, IHttpContextAccessor httpContextAccessor, SqlsugarDb<ReturnMoney> db)
        {
            this.mapper = mapper;

            this.httpContextAccessor = httpContextAccessor;
            this.db = db;
        }

        public async Task<ApiResult<int>> Handle(UpdateReturnMoneryCommand request, CancellationToken cancellationToken)
        {
            var result=new ApiResult<int>();

            try
            {

                var entity =await db.FirstQuery().FirstAsync(x => x.Id == request.Id);
                if (entity == null)
                {
                    result.message = "查无数据";
                    result.data = 0;
                    result.Code = Enumcode.fail;
                }
                 entity = mapper.Map(request,entity);
                entity.UpdateTime = DateTime.Now;
                entity.UpdateName = httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.Name)?.Value;
                entity.LoginId = Convert.ToInt32(httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier)?.Value);
                var returnrow = await db.Updata(entity);
                if (returnrow > 0)
                {
                    result.message = "修改收款信息成功";
                    result.data = 1;
                    result.Code = Enumcode.ok;
                }
                else
                {
                    result.message = "修改收款信息失败";
                    result.data = 0;
                    result.Code = Enumcode.fail;

                }


            }
            catch (Exception ex)
            {
                result.message =ex.Message;
                result.data = 0;
                result.Code = Enumcode.fail;
              
            }

            return await Task.FromResult(result); 
        }
    }
}
